import { DeleteOutline } from 'antd-mobile-icons'
import { Tag, Dialog } from 'antd-mobile'
import styles from '../css/city.module.css'
import { useDispatch, useSelector } from 'react-redux'
import {
  addSearchHistory,
  clearSearchHistory
} from '../../../store/slice/ticketSlice'
import { useNavigate, useParams } from 'react-router-dom'

function SearchHistory(props) {
  const list = useSelector((store) => store.ticket.searchHistory)
  const dispatch = useDispatch()
  const params = useParams()
  const nav = useNavigate()

  return (
    <div
      className={styles.historyBox}
      style={{ display: list.length === 0 ? 'none' : 'block' }}
    >
      {/* 标题 */}
      <div className={styles.titleBox}>
        <span className={styles.title}>搜索历史</span>
        {/* 删除的图标 */}
        <DeleteOutline
          className={styles.icon}
          onClick={() =>
            Dialog.confirm({
              content: '确认清空搜索历史吗？',
              // 点击确认，会触发 onConfirm 回调函数
              onConfirm() {
                // 调用仓库中提供的方法，清除搜索历史
                dispatch(clearSearchHistory())
              }
            })
          }
        />
      </div>

      {/* 搜索的历史 */}
      <div className={styles.tags}>
        {list.map((item, i) => (
          <Tag
            key={i}
            className={styles.tag}
            onClick={() => {
              // 把点击的城市存入搜索历史
              dispatch(addSearchHistory(item))
              // 把点击的城市存入出发地 或 目的地
              props.saveCity(params.type, item)
              // 导航后退
              nav(-1)
            }}
          >
            {item}
          </Tag>
        ))}
      </div>
    </div>
  )
}

export default SearchHistory
